//
//  AppDelegate.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "AppDelegate.h"
#import "GuideView.h"
#import "BaseTabBarViewController.h"
#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import "SelectNearProprieterController.h"

//以下是腾讯QQ和QQ空间
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>

#import "WXApi.h"
#import "WeiboSDK.h"

#import <ShareSDK/ShareSDK.h>

#import "GeTuiSdk.h"
#define kAppId           @"JFYMRLwGlx9QcfM1sC4pv8"
#define kAppKey          @"NlVdpLClNH8Yiqn5H4HMu3"
#define kAppSecret       @"gmtNfQ1NOmAtRU5tPpw1W4"

@interface AppDelegate ()<BMKLocationServiceDelegate,GeTuiSdkDelegate>
{
    BMKMapManager* _mapManager;
    BMKLocationService* _locService;
    NSInteger count;
    GuideView *guideView;  // 展示页
}
@property (strong, nonatomic) BaseTabBarViewController *tabVC;

@end

@implementation AppDelegate
- (void)initShare {
    /*
     懒猫社长(微信)
     AppID：wx274b4b066417cc12
     AppSecret：e7fa5fcab54c09608b3b6df111ac5cc6
     
     懒猫社长(新浪微博)
     App Key：26416955
     App Secret：2b97ce6168b6fac0d1cb9052901ad2bd
     
     
     懒猫社长(QQ)
     APP ID:1104856214
     APP KEY:lB1OHihDO8jJN6EA
     */
    [ShareSDK registerApp:@"a53854575753"];
    
    [ShareSDK connectSinaWeiboWithAppKey:@"26416955"
                               appSecret:@"2b97ce6168b6fac0d1cb9052901ad2bd"
                             redirectUri:@"http://www.sharesdk.cn"
                             weiboSDKCls:[WeiboSDK class]];
    [ShareSDK connectQZoneWithAppKey:@"1104856214"
                           appSecret:@"lB1OHihDO8jJN6EA"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
    [ShareSDK connectWeChatWithAppId:@"wx274b4b066417cc12"
                           appSecret:@"e7fa5fcab54c09608b3b6df111ac5cc6"
                           wechatCls:[WXApi class]];
    [ShareSDK connectQQWithQZoneAppKey:@"1104856214"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    [ShareSDK connectCopy];
}
- (void)registerRemoteNotification {
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    
    
    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
    
    // [2]:注册APNS
//    [self registerRemoteNotification];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    [self initShare];
    
    count = 0;

    //vB3d3HhCgAn7oiOgXPPbdO3j   com.zhanshu.lazycat
    //AMvNvxUstmO9ecdzzyXGtxog   com.zhan.push1
    //lf2SVe6g0Xj0sh4OLdzMVM5l   com.zskj.lichuan
    // 百度地图
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"lf2SVe6g0Xj0sh4OLdzMVM5l" generalDelegate:nil];
    
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    //取出店铺名称 店铺名称等相关信息 在选择之后保存在本地
    [AppData share].proprieter = [ShopCommonModel getShopMess].name;
#pragma mark - 判断是否第一次登录
    BOOL doFirst = ![[NSUserDefualManager getValueByKey:@"DoFirstLogin"] boolValue];
    [AppData share].doFirst = doFirst;
    if (doFirst) {
        //第一次启动 引导图
        [self theGuidedView];
    }else {
        _tabVC = [[BaseTabBarViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_tabVC];
        nav.navigationBarHidden = YES;
        self.window.rootViewController = nav;
    }
    [self.window makeKeyAndVisible];
    
    //定位
    [self locationPart];
    //监听网络
    [self theNetWorkConnectStates];
    
    //通知
    [self registerRemoteNotification];
    return YES;
}

#pragma mark - 网络判断
- (void)theNetWorkConnectStates {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"-------AFNetworkReachabilityStatusReachableViaWWAN------");
//                [[MessShowView share] showWithMess:@"当前网络--手机网络"];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"-------AFNetworkReachabilityStatusReachableViaWiFi------");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [[MessShowView share] showWithMess:@"当前网络不可用"];
                break;
            default:
                break;
        }
    }];
}
// 引导页
- (void)theGuidedView {
    NSLog(@"the hei %f",ScreenHeight);
    NSArray *imgArr ;
    if (ScreenHeight == 480) {
        imgArr = @[@"引导页01 960.png",@"引导页02 960.png",@"引导页03 960.png"];
    }else if (ScreenHeight == 568) {
        imgArr = @[@"引导页01 1136.png",@"引导页02 1136.png",@"引导页03 1136.png"];
    }else if (ScreenHeight == 1334/2) {
        imgArr = @[@"引导页01 1334.png",@"引导页02 1334.png",@"引导页03 1334.png"];
    }else if (ScreenHeight == 2208/3) {
        imgArr = @[@"引导页01 2208.png",@"引导页02 2208.png",@"引导页03 2208.png"];
    }
    
   guideView = [[GuideView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [guideView theGuideImg:imgArr];
    [guideView.endbtn addTarget:self action:@selector(endAction) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:guideView];
}
- (void)endAction {

    for (UIView *view in guideView.subviews) {
        [view removeFromSuperview];
    }
    [guideView removeFromSuperview],guideView = nil;
    SelectNearProprieterController *selectProprieter = [[SelectNearProprieterController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:selectProprieter];
    nav.navigationBarHidden = YES;
    self.window.rootViewController = nav;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    // [EXT] APP进入后台时，通知个推SDK进入后台
    [GeTuiSdk enterBackground];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    // [EXT] 重新上线
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void) stopSdk {
    [GeTuiSdk enterBackground];
}
#pragma mark- 定位
- (void)reLocation {
    count = 0;
    _locService = nil;
    [self locationPart];
}
- (void)locationPart {
    //定位
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [_locService startUserLocationService];
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //定位成功
    
    [AppData share].lat = userLocation.location.coordinate.latitude;
    [AppData share].lng = userLocation.location.coordinate.longitude;
    
    if (count == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:LC_Location_result object:[NSNumber numberWithBool:YES]];
        count = 1;
    }
    
}
- (void)didFailToLocateUserWithError:(NSError *)error {
    //定位失败
    if (count == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:LC_Location_result object:[NSNumber numberWithBool:NO]];
        count = 0;
    }
    
//    [AppData share].lat = 31.143887;
//    [AppData share].lng = 121.32719;
}
#pragma mark - 推送部分
#pragma mark - background fetch  唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    //[5] Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@", _deviceToken);
    
    // [3]:向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:_deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    [GeTuiSdk registerDeviceToken:@""];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userinfo {
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userinfo objectForKey:@"payload"];
    if (payloadMsg) {
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userInfo objectForKey:@"payload"];
    
    NSDictionary *aps = [userInfo objectForKey:@"aps"];
    NSNumber *contentAvailable = aps == nil ? nil : [aps objectForKeyedSubscript:@"content-available"];
    
    if (payloadMsg && contentAvailable) {
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@, [content-available: %@]", [NSDate date], payloadMsg, contentAvailable];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    
    NSError *err = nil;
    
    //[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self error:&err];
    
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    
}

- (void)setDeviceToken:(NSString *)aToken
{
    
    [GeTuiSdk registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error
{
    return [GeTuiSdk setTags:aTags];
}

- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    
    return [GeTuiSdk sendMessage:body error:error];
}

- (void)bindAlias:(NSString *)aAlias {
    [GeTuiSdk bindAlias:aAlias];
}

- (void)unbindAlias:(NSString *)aAlias {
    
    [GeTuiSdk unbindAlias:aAlias];
}
- (void)testGetClientId {
    NSString *clientId = [GeTuiSdk clientId];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"当前的CID" message:clientId delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

#pragma mark - GexinSdkDelegate
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId
{
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    if (_deviceToken) {
        [GeTuiSdk registerDeviceToken:_deviceToken];
    }
}

- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId fromApplication:(NSString *)appId
{
    // [4]: 收到个推消息
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
        NSLog(@"推送信息：%@",payloadMsg);
    }
    NSError *err;
    NSDictionary *messDic ;
    if (payload) {
         messDic = [NSJSONSerialization JSONObjectWithData:payload
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
    }
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return;
    }
    
    if (messDic) {
        if ([messDic isKindOfClass:[NSDictionary class]]) {
            NSString *title = [messDic[@"title"] safeString];
            NSString *type = [messDic[@"type"] safeString];
            BOOL doDetail = NO;
            if ([type isEqualToString:@"lanmao_notice"]) {
                doDetail = NO;
            }else if ([type isEqualToString:@"lanmao_product"]) {
                doDetail = YES;
            }else if ([type isEqualToString:@"lanmao_ad"]) {
                doDetail = NO;
            }else if ([type isEqualToString:@"lanmao_url"]) {
                doDetail = NO;
            }
            Html5ViewController *html5 = [[Html5ViewController alloc] init];
            html5.doDetailType = doDetail;
            html5.titleStr = title;
            html5.requestUrl = [messDic[@"url"] safeString];
            [[self getCurrentVC] presentViewController:html5 animated:YES completion:^{
                
            }];
        }
    }
    
}
- (UIViewController *)getCurrentVC
{
    UIViewController* activityViewController = nil;
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows)
        {
            if(tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    NSArray *viewsArray = [window subviews];
    if([viewsArray count] > 0)
    {
        UIView *frontView = [viewsArray objectAtIndex:0];
        
        id nextResponder = [frontView nextResponder];
        
        if([nextResponder isKindOfClass:[UIViewController class]])
        {
            activityViewController = nextResponder;
        }
        else
        {
            activityViewController = window.rootViewController;
        }
    }
    
    return activityViewController;
}
@end
